package com.pig.graduate.controller.finance;


import cn.hutool.core.date.DateUtil;
import cn.hutool.http.useragent.UserAgent;
import cn.hutool.http.useragent.UserAgentUtil;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pig.graduate.common.exception.MyException;
import com.pig.graduate.domain.finance.FinanceInfo;
import com.pig.graduate.result.MyResult;
import com.pig.graduate.service.financeInfo.FinanceInfoService;
import com.pig.graduate.util.IpUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@Api(tags = {"财务管理"}, description = "财务管理")
@RestController
@RequestMapping("/finance/info")
public class FinanceInfoController {

    @Autowired
    private FinanceInfoService financeInfoService;

    @ApiOperation(value = "财务数据",notes = "财务数据")
    @PostMapping("/list")
    public MyResult list(@RequestBody FinanceInfo financeInfo){
        if(financeInfo.getStartTime() == null && financeInfo.getEndTime() == null){
            String dateStr = "1970-01-01";
            Date date = DateUtil.parse(dateStr);
            financeInfo.setStartTime(date);
            financeInfo.setEndTime(new Date());
        }
        Page<FinanceInfo> financeInfoPage = new Page<>(financeInfo.getPageNum(),financeInfo.getPageSize());
        Page<FinanceInfo> page = new LambdaQueryChainWrapper<FinanceInfo>(financeInfoService.getBaseMapper())
                .like(FinanceInfo::getDataType, financeInfo.getDataType())
                .like(FinanceInfo::getIncomeExpensesType, financeInfo.getIncomeExpensesType())
                .ge(FinanceInfo::getCreateTime,financeInfo.getStartTime())
                .le(FinanceInfo::getCreateTime,financeInfo.getEndTime())
                .page(financeInfoPage);
        return MyResult.success(page);
    }

    @ApiOperation(value = "财务分析",notes = "财务分析")
    @GetMapping("/financialStatement")
    public MyResult financialStatement(@RequestParam("finaDate") String finaDate){
        return financeInfoService.financialStatement(finaDate);
    }


    @GetMapping("/test")
    public String test(HttpServletRequest httpRequest){
        String ip =IpUtil.getIpAddr(httpRequest);
        UserAgent userAgent = UserAgentUtil.parse(httpRequest.getHeader("user-agent"));
        try{
            return IpUtil.getIpPossession("183.157.194.114") + userAgent.getBrowser().toString();
        }catch (Exception e){
            e.printStackTrace();
        }
        return "未知异常";
    }

}
